package com.itheima.filter;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author Liuweipeng
* @date  2020/4/17
* @version v1.0
* @desc  页面过滤器
*/
public class HtmlFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;


        if (request.getRequestURI().indexOf("login") != -1 || request.getRequestURI().indexOf("Login") != -1){
            chain.doFilter(request,response);
        }else {
            Cookie[] cookies = request.getCookies();
            if(cookies != null) {
                for (Cookie cookie : cookies) {
                    String name = cookie.getName();
                    if (name.equals("JSESSIONID")) {
                        chain.doFilter(request, response);
                        return;
                    }
                }
            }
            response.sendRedirect("/pages/login.html");
        }
    }

    @Override
    public void destroy() {

    }
}
